"use client"

import { useState, useCallback, useEffect, useMemo } from "react"
import ReactFlow, {
  Node,
  Edge,
  addEdge,
  Background,
  Controls,
  MiniMap,
  Connection,
  useNodesState,
  useEdgesState,
  MarkerType,
  Panel,
} from "reactflow"
import "reactflow/dist/style.css"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { useToast } from "@/hooks/use-toast"
import { mockData } from "@/lib/mock-data"
import {
  Save,
  Play,
  Brain,
  DatabaseIcon,
  MessageSquare,
  Search,
  Calculator,
  FileText,
  Globe,
  Code,
  Eye,
  Edit3,
  type LucideIcon,
} from "lucide-react"

import { CustomNode } from "@/components/flow-nodes/custom-node"

const nodeTypes = {
  custom: CustomNode,
}

const componentTypeConfigs = [
  { id: "llm", type: "llm", label: "语言模型", iconName: "Brain", category: "核心" },
  { id: "memory", type: "memory", label: "记忆系统", iconName: "DatabaseIcon", category: "核心" },
  { id: "planner", type: "planner", label: "规划器", iconName: "MessageSquare", category: "核心" },
  { id: "search", type: "tool", label: "搜索工具", iconName: "Search", category: "工具" },
  { id: "calculator", type: "tool", label: "计算器", iconName: "Calculator", category: "工具" },
  { id: "document", type: "tool", label: "文档处理", iconName: "FileText", category: "工具" },
  { id: "api", type: "tool", label: "API 调用", iconName: "Globe", category: "工具" },
  { id: "code", type: "tool", label: "代码执行", iconName: "Code", category: "工具" },
]

const iconMap: Record<string, LucideIcon> = {
  Brain,
  DatabaseIcon,
  MessageSquare,
  Search,
  Calculator,
  FileText,
  Globe,
  Code,
}

interface AgentBuilderV2Props {
  agentId?: string
  mode?: "edit" | "view"
}

export function AgentBuilderV2({ agentId, mode = "edit" }: AgentBuilderV2Props) {
  const { toast } = useToast()
  const [agentName, setAgentName] = useState("未命名 Agent")
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [mounted, setMounted] = useState(false)
  const [viewMode, setViewMode] = useState<"edit" | "view">(mode)

  const [nodes, setNodes, onNodesChange] = useNodesState([])
  const [edges, setEdges, onEdgesChange] = useEdgesState([])

  useEffect(() => {
    setMounted(true)
  }, [])

  useEffect(() => {
    if (!mounted) return

    setIsLoading(true)
    if (agentId) {
      const agent = mockData.getAgent(agentId)
      if (agent) {
        setAgentName(agent.name)

        // Convert old format to React Flow format
        const flowNodes: Node[] =
          agent.components?.map((comp) => ({
            id: comp.id,
            type: "custom",
            position: { x: comp.x || 0, y: comp.y || 0 },
            data: {
              label: comp.label,
              type: comp.type,
              iconName: comp.config?.iconName,
              config: comp.config,
              onDelete: handleDeleteNode,
            },
          })) || []

        const flowEdges: Edge[] =
          agent.edges?.map((edge) => ({
            id: edge.id,
            source: edge.source,
            target: edge.target,
            type: "smoothstep",
            animated: true,
            markerEnd: {
              type: MarkerType.ArrowClosed,
            },
          })) || []

        setNodes(flowNodes)
        setEdges(flowEdges)
      }
    }
    setIsLoading(false)
  }, [agentId, mounted])

  const onConnect = useCallback(
    (params: Connection) => {
      setEdges((eds) =>
        addEdge(
          {
            ...params,
            type: "smoothstep",
            animated: true,
            markerEnd: {
              type: MarkerType.ArrowClosed,
            },
          },
          eds,
        ),
      )
    },
    [setEdges],
  )

  const onDragOver = useCallback((event: React.DragEvent) => {
    event.preventDefault()
    event.dataTransfer.dropEffect = "move"
  }, [])

  const onDrop = useCallback(
    (event: React.DragEvent) => {
      event.preventDefault()

      const type = event.dataTransfer.getData("application/reactflow")
      const label = event.dataTransfer.getData("label")
      const iconName = event.dataTransfer.getData("iconName")

      if (typeof type === "undefined" || !type) {
        return
      }

      const position = {
        x: event.clientX - 200,
        y: event.clientY - 100,
      }

      const newNode: Node = {
        id: `${type}-${Date.now()}`,
        type: "custom",
        position,
        data: {
          label,
          type,
          iconName,
          onDelete: handleDeleteNode,
        },
      }

      setNodes((nds) => nds.concat(newNode))
      toast({
        title: "组件已添加",
        description: `${label} 已添加到画布`,
      })
    },
    [setNodes, toast],
  )

  const handleDeleteNode = useCallback(
    (nodeId: string) => {
      setNodes((nds) => nds.filter((node) => node.id !== nodeId))
      setEdges((eds) => eds.filter((edge) => edge.source !== nodeId && edge.target !== nodeId))
      if (selectedNodeId === nodeId) {
        setSelectedNodeId(null)
      }
      toast({
        title: "组件已删除",
        description: "组件及其连接已从画布中移除",
      })
    },
    [setNodes, setEdges, selectedNodeId, toast],
  )

  const handleSave = () => {
    const agentData = {
      name: agentName,
      components: nodes.map((node) => ({
        id: node.id,
        type: node.data.type,
        label: node.data.label,
        x: node.position.x,
        y: node.position.y,
        config: { iconName: node.data.iconName },
      })),
      edges: edges.map((edge) => ({
        id: edge.id,
        source: edge.source,
        target: edge.target,
      })),
    }

    if (agentId) {
      mockData.updateAgent(agentId, agentData)
      toast({
        title: "保存成功",
        description: "Agent 已更新",
      })
    } else {
      mockData.addAgent({
        ...agentData,
        status: "draft",
        lastRun: "从未运行",
        createdAt: new Date().toISOString().split("T")[0],
      })
      toast({
        title: "保存成功",
        description: "新 Agent 已创建",
      })
    }
  }

  const handleTest = () => {
    toast({
      title: "测试运行中",
      description: "Agent 正在执行测试...",
    })
    setTimeout(() => {
      toast({
        title: "测试完成",
        description: "Agent 执行成功",
      })
    }, 2000)
  }

  const onDragStart = (event: React.DragEvent, config: any) => {
    event.dataTransfer.setData("application/reactflow", config.type)
    event.dataTransfer.setData("label", config.label)
    event.dataTransfer.setData("iconName", config.iconName)
    event.dataTransfer.effectAllowed = "move"
  }

  const selectedNode = useMemo(() => {
    return nodes.find((node) => node.id === selectedNodeId)
  }, [nodes, selectedNodeId])

  const handleNodeClick = useCallback(
    (_: React.MouseEvent, node: Node) => {
      setSelectedNodeId(node.id)
    },
    [setSelectedNodeId],
  )

  const updateNodeData = useCallback(
    (nodeId: string, newData: Partial<any>) => {
      setNodes((nds) =>
        nds.map((node) => {
          if (node.id === nodeId) {
            return {
              ...node,
              data: {
                ...node.data,
                ...newData,
              },
            }
          }
          return node
        }),
      )
    },
    [setNodes],
  )

  if (!mounted || isLoading) {
    return (
      <div className="h-[calc(100vh-8rem)] flex items-center justify-center">
        <div className="text-center space-y-2">
          <div className="h-8 w-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto" />
          <p className="text-sm text-muted-foreground">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-[calc(100vh-8rem)] flex flex-col gap-4">
      {/* Toolbar */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Input
            value={agentName}
            onChange={(e) => setAgentName(e.target.value)}
            className="w-64 font-semibold"
            disabled={viewMode === "view"}
          />
          <Badge variant="outline" className="gap-1">
            <Brain className="h-3 w-3" />
            LangGraph Agent
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setViewMode(viewMode === "edit" ? "view" : "edit")}
          >
            {viewMode === "edit" ? (
              <>
                <Eye className="mr-2 h-4 w-4" />
                查看模式
              </>
            ) : (
              <>
                <Edit3 className="mr-2 h-4 w-4" />
                编辑模式
              </>
            )}
          </Button>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={handleTest}>
            <Play className="mr-2 h-4 w-4" />
            测试
          </Button>
          {viewMode === "edit" && (
            <Button onClick={handleSave}>
              <Save className="mr-2 h-4 w-4" />
              保存
            </Button>
          )}
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 grid grid-cols-[280px_1fr_320px] gap-4 min-h-0">
        {/* Component Library */}
        {viewMode === "edit" && (
          <Card className="flex flex-col">
            <CardHeader className="pb-3">
              <CardTitle className="text-base">组件库</CardTitle>
              <CardDescription>拖拽组件到画布</CardDescription>
            </CardHeader>
            <CardContent className="flex-1 p-0">
              <ScrollArea className="h-full px-4 pb-4">
                <div className="space-y-4">
                  {["核心", "工具"].map((category) => (
                    <div key={category} className="space-y-2">
                      <h4 className="text-sm font-medium text-muted-foreground">{category}</h4>
                      <div className="space-y-1">
                        {componentTypeConfigs
                          .filter((config) => config.category === category)
                          .map((config) => {
                            const IconComponent = iconMap[config.iconName]
                            return (
                              <div
                                key={config.id}
                                draggable
                                onDragStart={(e) => onDragStart(e, config)}
                                className="flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-accent cursor-move transition-colors"
                              >
                                <div className="h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                                  <IconComponent className="h-4 w-4 text-primary" />
                                </div>
                                <span className="text-sm font-medium">{config.label}</span>
                              </div>
                            )
                          })}
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        )}

        {/* Canvas */}
        <Card className={`relative overflow-hidden ${viewMode === "edit" ? "" : "col-span-2"}`}>
          <ReactFlow
            nodes={nodes}
            edges={edges}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            onConnect={onConnect}
            onDrop={onDrop}
            onDragOver={onDragOver}
            onNodeClick={handleNodeClick}
            nodeTypes={nodeTypes}
            fitView
            nodesDraggable={viewMode === "edit"}
            nodesConnectable={viewMode === "edit"}
            elementsSelectable={viewMode === "edit"}
          >
            <Background />
            <Controls />
            <MiniMap
              nodeColor={(node) => {
                const colors: Record<string, string> = {
                  llm: "#a855f7",
                  memory: "#10b981",
                  planner: "#f59e0b",
                  tool: "#8b5cf6",
                  default: "#6b7280",
                }
                return colors[node.data.type] || colors.default
              }}
              maskColor="rgb(0, 0, 0, 0.1)"
            />
            <Panel position="top-left">
              <Badge variant="outline" className="bg-background">
                {viewMode === "edit" ? "编辑模式" : "查看模式"}
              </Badge>
            </Panel>
          </ReactFlow>
        </Card>

        {/* Properties Panel */}
        {viewMode === "edit" && (
          <Card className="flex flex-col">
            <CardHeader className="pb-3">
              <CardTitle className="text-base">组件配置</CardTitle>
              <CardDescription>配置选中组件</CardDescription>
            </CardHeader>
            <CardContent className="flex-1">
              {selectedNode ? (
                <ScrollArea className="h-full">
                  <div className="space-y-4">
                    <div className="space-y-2">
                      <Label>组件名称</Label>
                      <Input
                        value={selectedNode.data.label}
                        onChange={(e) => {
                          updateNodeData(selectedNode.id, { label: e.target.value })
                        }}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>组件类型</Label>
                      <Input value={selectedNode.data.type} disabled />
                    </div>

                    {selectedNode.data.type === "llm" && (
                      <>
                        <div className="space-y-2">
                          <Label>模型选择</Label>
                          <Input placeholder="gpt-4" />
                        </div>
                        <div className="space-y-2">
                          <Label>系统提示词</Label>
                          <Textarea placeholder="你是一个有帮助的 AI 助手..." className="min-h-[100px] resize-none" />
                        </div>
                        <div className="space-y-2">
                          <Label>温度</Label>
                          <Input type="number" placeholder="0.7" step="0.1" min="0" max="2" />
                        </div>
                      </>
                    )}

                    {selectedNode.data.type === "memory" && (
                      <>
                        <div className="space-y-2">
                          <Label>记忆类型</Label>
                          <Input placeholder="对话历史" />
                        </div>
                        <div className="flex items-center justify-between">
                          <Label>启用长期记忆</Label>
                          <Switch />
                        </div>
                        <div className="space-y-2">
                          <Label>最大记忆条数</Label>
                          <Input type="number" placeholder="100" />
                        </div>
                      </>
                    )}

                    {selectedNode.data.type === "tool" && (
                      <>
                        <div className="space-y-2">
                          <Label>工具描述</Label>
                          <Textarea placeholder="描述这个工具的功能..." className="min-h-[80px] resize-none" />
                        </div>
                        <div className="space-y-2">
                          <Label>参数配置</Label>
                          <Input placeholder='{"param1": "value1"}' />
                        </div>
                        <div className="flex items-center justify-between">
                          <Label>需要确认</Label>
                          <Switch />
                        </div>
                      </>
                    )}
                  </div>
                </ScrollArea>
              ) : (
                <div className="flex items-center justify-center h-full text-sm text-muted-foreground text-center px-4">
                  <div className="space-y-2">
                    <p>选择一个组件查看配置</p>
                    <p className="text-xs">点击组件可查看和编辑其属性</p>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}
